package com.stormrage.edu.ctrl.edu;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.edu.EduLecServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.edu.EduLec;
import com.stormrage.entity.edu.req.EduLecReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;
import com.stormragetech.core.exception.StormrageTechException;

/**
 * @Title: EduLecCtrl.java
 * @Package com.stormrage.edu.ctrl
 * @Description: 讲师 Controller
 * @author www.stormragetech.com
 * @date 2016年4月10日
 * @version V1.0
 */
@Controller
@RequestMapping("/lec")
public class EduLecCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(EduCourseCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['path.root']}")
	private String rootPath;

	@Value("#{constants['path.image']}")
	private String imagePath;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EduLecServ eduLecServ;

	@RequiresPermissions("lec:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Create 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Create 】-【 GET 】- 结束运行 ");
		return "edu/lec/create";

	}

	@RequiresPermissions("lec:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr, EduLec entity, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Create 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file) {

			StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "您没有上传讲师图片",
					StormrageTechException.ERR_APP, "【 EduCourseCtrl 】-【 Create 】");

			err = ErrorRep.instance(false, exception.getMessage());
			redirect.addFlashAttribute("err", err);

			return "redirect:/lec/create";
		}

		try {

			String fileName = eduLecServ.upload(file, rootPath + imagePath);
			entity.setImage(fileName);

			// ------------------ Ctrl操作 ------------------

			eduLecServ.create(entity);
			errMsg = "提示信息：添加讲师成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加讲师失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/lec/list";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Create 】-【 POST 】- 结束运行 ");
		return "redirect:/lec/list";

	}

	@RequiresPermissions("lec:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			EduLec entity = eduLecServ.queryById(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);
			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/lec/edit";

	}

	@RequiresPermissions("lec:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, EduLec entity,
			@RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		logger.debug(" caonima " + entity.toString());

		try {

			if (null != file && file.getBytes().length > 0) {
				String fileName = eduLecServ.upload(file, rootPath + imagePath);
				entity.setImage(fileName);
			}

			// ------------------ Ctrl操作 ------------------
			eduLecServ.update(entity);
			errMsg = "提示信息：修改讲师信息成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改讲师信息失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/lec/list";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 POST 】- 结束运行 ");
		return "redirect:/lec/list";

	}

	@RequiresPermissions("lec:del")
	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Delete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduLecServ.delete(id);
			errMsg = "提示信息：删除讲师成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除讲师失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/lec/list";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Delete 】-【 GET 】- 结束运行 ");
		return "redirect:/lec/list";

	}

	@RequiresPermissions("lec:edit")
	@RequestMapping(value = "/idx/{id}", method = RequestMethod.GET)
	public String idx(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 idx 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduLecServ.updateIdx(id);
			errMsg = "提示信息：修改讲师首页显示状态成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改讲师首页显示状态失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/lec/list";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 idx 】-【 GET 】- 结束运行 ");
		return "redirect:/lec/list";

	}

	@RequiresPermissions("lec:view")
	@RequestMapping(value = "/list")
	public String list(@CurrentUser ShiroAcct curr, EduLecReq req, Model model) {

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduCourseCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/lec/list";
	}

	@RequiresPermissions("lec:view")
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, EduLecReq req) {

		logger.debug(" 【 Controller 】- 【 EduCourseCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduLecServ.queryList(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduCourseCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

}
